import { defineStore } from "pinia"
import { computed, ref } from "vue"
import { useUserStore } from "./user"
import { deleteCart, getCartList, insertCart } from "@/apis/cart"
export const useCartStore = defineStore('cart', () => {
  // 购物车列表
  const cartList = ref([])
  const getCart = async () => {
    // 获取购物车列表
    const res = await getCartList()
    cartList.value = res.data.result
  }

  // 添加到购物车
  const addCart = async (goods) => {
    const userStore = useUserStore()
    // 判断是否登录
    if (userStore.userInfo.token) {
      console.log('登录了')

      // 加入购物车
      await insertCart({ skuId: goods.skuId, count: goods.count })
      // 获取购物车列表
      getCart()
    } else {
      console.log('未登录')

      // 判断购物车是否存在该商品
      const item = cartList.value.find(item => item.skuId === goods.skuId)
      if (item) {
        // 存在就加上购物车数量
        item.count += goods.count
      } else {
        // 不存在就添加到购物车
        cartList.value.push(goods)
      }
    }
  }

  // 删除购物车
  const delCart = async (skuId) => {
    const userStore = useUserStore()
    if (userStore.userInfo.token) {
      // 删除购物车内容
      await deleteCart([skuId])
      // 更新购物车内容
      getCart()
    } else {
      // 根据skuId找到要删除的商品
      const index = cartList.value.findIndex(item => item.skuId === skuId)
      // 删除
      cartList.value.splice(index, 1)
    }
  }

  // 清除购物车数据
  const clearCart = () => {
    cartList.value = []
  }

  // 更改复选框状态
  const changeCheckBox = (value, skuId) => {
    const item = cartList.value.find(item => item.skuId === skuId)

    item.selected = value
  }

  // 购物车商品列表数量
  const cartTotal = computed(() => cartList.value.length)
  // 总和
  const total = computed(() => cartList.value.reduce((sum, item) => sum + item.count, 0))

  // 结算
  const priceTotal = computed(() => cartList.value.reduce((sum, item) => sum + item.count * item.price, 0).toFixed(2))

  // 是否全选
  const isAll = computed(() => cartList.value.every(item => item.selected))

  // 全选
  const selecteAll = (value) => {
    cartList.value.forEach(item => item.selected = value)
  }

  // 被选中的商品数量
  const selecteGoods = computed(() => cartList.value.filter(item => item.selected).length)
  // 被选中商品合计
  const selectePricetotle = computed(() => {
    let total = 0
    cartList.value.forEach(item => {
      if (item.selected) {
        total += item.count * item.price
      }
    })

    return total.toFixed(2)
  })
  return {
    cartList,
    addCart,
    delCart,
    total,
    priceTotal,
    changeCheckBox,
    isAll,
    selecteAll,
    clearCart,
    getCart,
    selecteGoods,
    selectePricetotle,
    cartTotal
  }
}, {
  persist: true
})
